/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package uk.ac.sanger.solr;

import java.io.*;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.biodas.jdas.client.TypesClient;
import org.biodas.jdas.client.adapters.types.DasTypesAdapter;
import org.biodas.jdas.dassources.utils.RegistrySourceAdapter;
import org.biodas.jdas.exceptions.DASClientException;
import org.biodas.jdas.exceptions.ValidationException;
import org.biodas.jdas.schema.sources.*;
import org.biodas.jdas.schema.types.DASTYPES;
import org.biodas.jdas.schema.types.SEGMENT;
import org.biodas.jdas.schema.types.TYPE;
import org.springframework.web.client.RestTemplate;

/**
 *
 * @author jw12
 */
public class CreateSolrTypesIndexes {

    private String nl;
    private final CreateSolrIndexerUtil util;

    public static void main(String[] args) {
        String homeDir = "/Users/jw12/tmp/";//args[0];

        CreateSolrTypesIndexes indexer = new CreateSolrTypesIndexes();
        indexer.createSolrIndex(homeDir);
    }

    public CreateSolrTypesIndexes(){
        util = new CreateSolrIndexerUtil();
        nl = util.getLineSeperator();
    }
    public void createSolrIndex(String homeDir) {
//        if (!homeDir.endsWith("/")) {
//            homeDir += homeDir + "/";
//        }
        


        RestTemplate temp = new RestTemplate();
        //get sources with valid types command only
        SOURCES sources = temp.getForObject("http://www.dasregistry.org/" + "das/sources?validCapabilities=types", SOURCES.class);
        int totalSources = sources.getSOURCE().size();



        File file = new File(homeDir + "solrTypes.xml");
        OutputStreamWriter out = null;
        try {
            out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            //  Auto-generated catch block
            e1.printStackTrace();
        } catch (FileNotFoundException e1) {
            //  Auto-generated catch block
            e1.printStackTrace();
        }
        System.out.println("writing sources for solrIndexer at " + file.getAbsolutePath());

        PrintWriter writer = null;
        writer = new PrintWriter(out);
        //NEED to add code to remove <a href from any fields!!!!
        writer.write("<add overwrite=\"true\" commitWithin=\"10000\">" + nl);
        int i = 1;
        for (SOURCE source : sources.getSOURCE()) {
            //if(i>=210 && i<220){
            try {
                this.writeSolrType(source, writer);
                
                System.out.println(i + " of " + totalSources + " total sources");
            } catch (DASClientException ex) {
                System.out.println("got to dasclient exception");
               Logger.getLogger(CreateSolrTypesIndexes.class.getName()).log(Level.SEVERE, null, ex);
              
            } catch (ValidationException ex) {
               Logger.getLogger(CreateSolrTypesIndexes.class.getName()).log(Level.SEVERE, null, ex);
               
            }
            //}
            i++;
        }
        writer.write("</add>");
        writer.flush();
        writer.close();
    }

    /**
     * method to get Types from the original data source and then put this into
     * the solrIndex file
     *
     * @param source
     * @param writer
     */
    void writeSolrType(SOURCE source, PrintWriter out) throws ValidationException, DASClientException {

        RegistrySourceAdapter regAdapter = new RegistrySourceAdapter(source);
        String uri = regAdapter.getOriginalDataSourceUri();
        System.out.println(" source uri=" + uri);
        List<TYPE> types = this.getTypesForSource(uri);
        if(types!=null && !types.isEmpty()){
        for (TYPE type : types) {
            //out.write("<doc>" + nl);
            createField(out, "typeId", type.getId());
            createField(out, "typeDescription", type.getDescription());
            createField(out, "cvId", type.getCvId());
            createField(out, "number", type.getValue());
            //out.write("</doc>" + nl);
        }
        }

    }

    List<TYPE> getTypesForSource(String sourceUri) throws DASClientException {

        TypesClient client = new TypesClient();
        //get sources with valid types command only

        DasTypesAdapter types = client.fetchData(sourceUri);
        int size = types.getGff().getSegments().size();
        // System.out.println("size="+size);
        //DasTypesAdapter adapt=new DasTypesAdapter(types);
        //return adapt.getGff().getSegments().get(0).getTYPE();
        SEGMENT seg = (SEGMENT) types.getGff().getSegments().get(0);
        return seg.getTYPE();
    }

    private void createField(PrintWriter out, String name, String content) {
        util.createField(out, name, content);
    }
}
